package com.buka.blog.dao;

import com.buka.blog.entity.Blog;
import com.buka.user.controller.UserLoginServlet;
import com.buka.utils.JDBCUtil;

import java.util.ArrayList;
import java.util.List;

public class BlogDao {

    /**
     *
     * @param pageNum  当前的页码
     * @param pageSize 每页显示的记录数
     * @return
     */
    public List<Blog> list(int pageNum,int pageSize) {
        int startIndex = (pageNum - 1) * pageSize;//当前页的开始索引
        //排除掉已删除的和未发布的
        String sql = "select * from blog where deleteflag = 0 and status = 1 limit ?,?";//全部博客
        return JDBCUtil.executeQuery(sql, Blog.class,startIndex,pageSize);
    }

    /**
     * 我的博客
     */
    public List<Blog> listByUser(Long userId) {
        String sql = "select * from blog where deleteflag = 0 and userid = ?";
        return JDBCUtil.executeQuery(sql, Blog.class, userId);
    }

    /***
     * 删除博客（批量删除）
     */
    public int delete(Long[] ids) {
        String sql = "update blog set deleteflag = 1 where id in (";
        for (int i = 0; i < ids.length; i++) {
            sql += "?,";
        }
//        String sql = "update blog set deleteflag = 1 where id in (?,?)"
        //每次拼接 ？，  拼接完成字符串结尾多一个逗号，去除末尾逗号
        sql = sql.substring(0, sql.length() - 1);
        sql += ")";
        return JDBCUtil.executeUpdateByArr(sql, ids);
    }

    public int add(Blog blog) {
        String sql = "insert into blog(title,content,userid,status,deleteflag,createTime) values(?,?,?,?,?,?)";
        return JDBCUtil.executeUpdateByArr(sql, blog.getTitle(), blog.getContent(), blog.getUserId(), blog.getStatus(), blog.getDeleteFlag(), blog.getCreateTime());
    }

    public long totalCount() {
        String sql = "select count(*) from blog where deleteflag = 0 and status = 1";
        //查询语句返回的是记录数，为数值类型  对应java的int 或 long
        List<Long> objects = JDBCUtil.executeQuery(sql, Long.class);
        return objects.get(0);
    }
}
